<template>
  <div class="contBody">
    <h2 class="title">OpenLayers 地图</h2>
    <div id="map" class="map__x"></div>
    <div id="mousePosition" class="mousePosition"></div>
    <div class="btn">
      <el-button type="primary" @click="layerHide">图层隐藏</el-button>
      <el-button type="primary" @click="panto">平移</el-button>
      <el-button type="primary" @click="flyHandle([113.15, 23.08])">
        飞到广州
      </el-button>
      <el-button type="primary" @click="flyHandle([116.403119, 39.918034])">
        飞到北京
      </el-button>
    </div>
  </div>
</template>

<script>
import { Map, View } from "ol"; // 地图实例方法、视图方法
import TileLayer from "ol/layer/Tile.js"; // 瓦片渲染方法
import { defaults as defaultControls, OverviewMap } from "ol/control.js";
import ScaleLine from "ol/control/ScaleLine";
import FullScreen from "ol/control/FullScreen";
import { createStringXY } from "ol/coordinate";
import MousePosition from "ol/control/MousePosition";
import XYZ from "ol/source/XYZ.js";
import "ol/ol.css"; // 地图样式

export default {
  name: "MapPage",
  data() {
    return {
      map: null,
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      //实例化鼠标位置控件（MousePosition）
      const mousePositionControl = new MousePosition({
        //坐标格式
        coordinateFormat: createStringXY(4),
        //地图投影坐标系（若未设置则输出为默认投影坐标系下的坐标）
        projection: "EPSG:4326",
        //坐标信息显示样式类名，默认是'ol-mouse-position'
        className: "mousePosition",
        //显示鼠标位置信息的目标容器
        target: document.getElementById("mousePosition"),
        //未定义坐标的标记
        undefinedHTML: "&nbsp;",
      });

      //实例化比例尺控件（ScaleLine）
      const scaleLineControl = new ScaleLine({
        //设置比例尺单位，degrees、imperial、us、nautical、metric（度量单位）
        units: "metric",
      });

      //实例化鹰眼控件（OverviewMap）,最简单的默认样式鹰眼控件
      const overviewMapControl = new OverviewMap({
        className: "ol-overviewmap ol-custom-overviewmap",
        layers: [
          new TileLayer({
            source: new XYZ({
              url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
              wrapX: false,
            }),
          }),
        ],
        //鹰眼控件展开时功能按钮上的标识（网页的JS的字符编码）
        collapseLabel: "\u00BB",
        //鹰眼控件折叠时功能按钮上的标识（网页的JS的字符编码）
        label: "\u00AB",
        //初始为展开显示方式
        collapsed: true,
      });
      console.log(overviewMapControl);

      // 全屏
      const FullScreenControl = new FullScreen();

      // 地图实例
      this.map = new Map({
        target: "map", // 对应页面里 id 为 map 的元素
        layers: [
          // 图层
          new TileLayer({
            title: "天地图矢量图层",
            source: new XYZ({
              url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=200d3f62135e4debe4f843220883e31d",
              // attributions: "天地图的属性描述",
              wrapX: false,
            }),
            preload: Infinity,
            zIndex: 1,
            visible: true,
          }),

          new TileLayer({
            title: "天地图矢量图层注记",
            source: new XYZ({
              url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=200d3f62135e4debe4f843220883e31d",
              // attributions: "天地图的属性描述",
              wrapX: false,
            }),
            preload: Infinity,
            zIndex: 1,
            visible: true,
          }),
        ],
        view: new View({
          // 地图视图
          projection: "EPSG:4326", // 坐标系，有EPSG:4326和EPSG:3857
          center: [100.864943, 24.041115], // 云南坐标
          minZoom: 5, // 地图缩放最小级别
          zoom: 6, // 地图缩放级别（打开页面时默认级别）
          // rotation: Math.PI / 6, //设置旋转角度
        }),
        //加载控件到地图容器中
        controls: defaultControls({
          //地图中默认控件
          attributionOptions: {
            //地图数据源信息控件是否可收缩,默认为true
            collapsible: true,
          },
        }).extend([
          mousePositionControl, // 加载鼠标位置控件
          scaleLineControl, // 比例尺
          // overviewMapControl, // 鹰眼
          FullScreenControl, // 全屏
        ]),
      });
    },
    panto() {
      const view = this.map.getView();
      const tam = [116.403119, 39.918034];
      //平移地图到天安门
      view.setCenter(tam);
      view.setZoom(13);
    },
    layerHide() {
      const layers = this.map.getLayers();
      // 图层隐藏
      layers.item(1).setVisible(false);
    },
    flyHandle(cityName) {
      const view = this.map.getView();
      const duration = 2000; //动画的持续时间（以毫秒为单位）
      const zoom = 6;
      let parts = 2;
      let called = false;

      //动画完成的回调函数
      function callback(complete) {
        --parts;
        if (called) {
          return;
        }
        if (parts === 0 || !complete) {
          called = true;
          // done(complete);
        }
      }
      //第一个动画
      view.animate(
        {
          center: cityName,
          duration: duration,
        },
        callback
      );
      //第二个动画
      view.animate(
        {
          zoom: zoom - 1,
          duration: duration / 2,
        },
        {
          zoom: zoom + 5,
          duration: duration / 2,
        },
        callback
      );
    },
  },
};
</script>

<style lang="css" scoped>
.contBody .title {
  padding: 0 0 24px;
}
.map__x {
  width: 100%;
  height: 600px;
  border: 1px solid #eee;
  /* 1.设置地图背景色 */
  background: rgba(0, 0, 0, 1);
}

.btn {
  text-align: left;
}

.mousePosition {
  text-align: left;
  color: rgb(0, 0, 0);
  font-size: 16px;
  font-family: "微软雅黑";
}
</style>

<style>
.ol-overviewmap {
  bottom: auto;
  left: auto;
  right: 0;
  top: 0;
}
</style>
